import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/ManageView.vue'
import LoginView from "@/views/LoginView";
import store from "@/store";

Vue.use(VueRouter);

/* 在创建router实例对象之前，手动覆盖原型链的push来吞掉报错catch */
// 先存储默认底层的push
const originPush = VueRouter.prototype.push;
// 覆盖原型链的push
VueRouter.prototype.push = function (location, resolve, reject) {
    // this:路由实例对象
    // 判断用户有没有传后面两个可选参数
    if (resolve || reject) {
        return originPush.call(this, location, resolve, reject)
    } else {// 用户只传了第一个参数
        /*
        默认底层： catch()方法代码  throw err : 抛出异常
        吞掉报错原理： 重写catch()方法,把默认底层的 throw err给去掉，就不会抛出异常
        */
        return originPush.call(this, location).catch(err => {
            //  throw err
        });
    }
};

const routes = [
    /*{
        path: '/', name: 'home', component: HomeView, redirect: '/home',
        children: [
            {path: '/home', name: 'Home', meta: {desc: "主页"}, component: () => import('@/views/HomeView')},
            {path: '/user', name: 'User', meta: {desc: "用户管理"}, component: () => import('@/views/UserView')},
            {path: '/role', name: 'Role', meta: {desc: "权限管理"}, component: () => import('@/views/RoleView')},
            {path: '/menu', name: 'Menu', meta: {desc: "菜单管理"}, component: () => import('@/views/MenuView')},
            {path: '/person', name: 'Person', meta: {desc: "个人信息"}, component: () => import('@/views/Person')},
            {path: '/file', name: 'File', meta: {desc: "文件管理"}, component: () => import('@/views/FileView')},
        ]
    },*/
    {path: '/login', name: 'Login', component: () => import('@/views/LoginView')},
    {path: '/register', name: 'Register', component: () => import('@/views/RegisterView')},
    {path: '/error', name: 'Error', component: () => import('@/views/ErrorView')},
    {path: '/front', name: 'Front', component: () => import('@/views/front/Front'),
        children: [{path: 'home', name: 'Home', component: () => import('@/views/front/Home')},
            {path: '/front/person', name: 'frontPerson', component: () => import('@/views/front/frontPerson')}
        ]},
];

//重置路由
export const resetRoutes = () => {
    router.matcher = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    });
}

//权限动态加载路由,bug1:只在login时加载其他页面刷新路由消失
export const setRoutes = () => {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {

        //获取当前路由对象名称数组
        const currentRouteNames = router.getRoutes().map(value => value.name);
        if (!currentRouteNames.includes('manage')) {
            const manageRoute = {
                path: '/', name: 'manage', component: HomeView, redirect: '/home', children: [
                    {path: '/person', name: 'Person', meta: {desc: "个人信息"}, component: () => import('@/views/PersonView')},
                ]
            };
            const menus = JSON.parse(storeMenus);
            menus.forEach(item => {
                if (item.path) {//当且仅当当前path不为空时设置路由
                    let itemMenu = {
                        path: item.path.replace("/", ""),
                        name: item.name,
                        meta: {desc: item.name},
                        component: () => import('@/views/' + item.pagePath + '.vue')
                    };
                    manageRoute.children.push(itemMenu);
                } else if (item.children.length) {
                    item.children.forEach(item => {
                        if (item.path) {
                            let itemMenu = {
                                path: item.path.replace("/", ""),
                                name: item.name,
                                meta: {desc: item.name},
                                component: () => import('@/views/' + item.pagePath + '.vue')
                            }
                            manageRoute.children.push(itemMenu);
                        }
                    })
                }
            })
            router.addRoute(manageRoute);
        }
    }
}

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});

//路由守卫
router.beforeEach((to, from, next) => {
    localStorage.setItem("currentPathName", to.meta.desc);//设置当前路由名称，再header中使用
    store.commit("setPath");//触发store的数据更新
    //未找到路由
    if (!to.matched.length) {
        let storeMenus = localStorage.getItem("menus");
        if (storeMenus) {//有菜单跳404
            next("/error");
        } else {
            router.push("login");
            //next("/login");
        }
    }
    next()//放行
});

//每次刷新时加载，解决bug1
setRoutes();

export default router
